<script>
// let baseUrl = 'http://localhost:8080'
import {readExcelToJson, saveJsonToExcel} from '../utils.js'
import axios from "axios";
import log from "echarts/src/scale/Log";

export default {
  data() {
    return {
      file: null,   // 导出
      SysOperLog: {
        operId: '',
        title: '',
        businessType: '',
        method: '',
        requestMethod: '',
        operatorType: '',
        operName: '',
        deptName: '',
        operUrl: '',
        operIp: '',
        operLocation: '',
        operParam: '',
        jsonResult: '',
        status: '',
        errorMsg: '',
        operTime: '',
      },
      SysOperLogAndDate: {
        current: '',
        size: '',
        startDate: '',
        endDate: '',
        status: '',
        /*系统模块——模块标题*/
        title: '',
        /*操作人员*/
        operName: '',
        //业务类型（0其它 1新增 2修改 3删除 4导入 5导出 6授权 7强退 8生成代码 9清除缓存）
        businessType: '',
      },
      /*回填数据*/
      SysOperLogBackfill:{
        operBusiness:'',
        reqPath:'',
        userIdIter:'',
        reqMethod:'',
        operMethodPath:'',
        reqParameter:'',
        respParameter:'',
        loginStatus:'',
        operTime:'',
      },
      AllJudge: '', // 获取所有的类型
      visible: false, // 弹出确认框
      dateTimeFile: '', // 查询时间范围
      dialogVisible: false, // 开启弹框
      selectionLength: 0, // 多选框被选中个数
      selectionList: [],  // 多选框被选中集合
      SysOperLogS: [],//用户列表
      SysOperLogAll: [],//所有的用户列表
      dateName: '',  // 导出命名
      boxSize :"small", // 弹出框大小
      current: 1,     // 当前页数
      size: 10,        // 每页条数
      pages: 1,       // 页面数
      total: 0,       // 总条数

      /*日期快捷选择*/
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  methods: {
    log,
    /*导出为excel*/
    // 读取文件为json数据
    onUploadChange(file) {
      this.file = file
      readExcelToJson(file).then((res) => {
        this.sysOperLogs = res
      })
    },
    // 导出文件名
    handleDownload(dataName) {
      if (dataName === '') {
        dataName = 'default';
      }
      if (this.selectionList.length === 0) {
        saveJsonToExcel(this.SysOperLogAll, dataName + '.xlsx')
        console.log("=====================")
        console.log(dataName)
      } else {
        axios.post("http://localhost:8080/sysOperLog-exportNumber", this.selectionList)
            .then(result => {
              saveJsonToExcel(result.data.data, dataName + '.xlsx')
            })
      }
      this.isNull();
      this.openYes("导出成功");
    },
    // 清空输入框
    isNull() {
      this.dateName = '';
    },
    /*删除多条数据*/
    deleteSomeSysOperLog() {
      //删除逻辑
      if (this.selectionList.length === 0) {
        this.openWarning("请选择后再删除")
      } else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios({
            headers: {
              'Content-Type': 'application/json'
            },
            method: "post",
            url: "http://localhost:8080/sysOperLog-some",
            //指定 json 类型后，传输的数据理所当然应该是 json 格式。
            data: this.selectionList
          })
              .then(() => {
                console.log('成功');
                this.loadFindPage(this.current);
                this.openYes("成功删除")
              })
              .catch(() => {
                console.log('失败');
                this.loadFindPage(this.current);
              });
        }).catch(() => {
          console.log("取消删除");
        });
      }
    },
    /*询问是否需要关闭*/
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.openNotice('已关闭')
            done();
          })
          .catch(_ => {
          });
    },
    /*获取所有数据*/
    loadAll () {
      axios.post("http://localhost:8080/sysOperLog-all")
          .then(result => {
            this.SysOperLogAll = result.data.data;
          })
      console.log("获取所有记录")
    },
    /*调用字典接口，获取操作类型字段*/
    getAllJudge() {
      axios.get("http://localhost:8080/sysDictData-find?dictType=sys_oper_type")
          .then(result => {
            this.AllJudge = result.data.data
            console.log(this.AllJudge)
          })
      console.log("获取操作类型数据")
    },
    /*查询数据*/
    loadFindPage(current) {
      this.current = current;
      if(this.SysOperLogAndDate.status !== ''){
        this.SysOperLogAndDate.status = this.SysOperLogAndDate.status === '开启'?1:0;
      }
      if (this.dateTimeFile.length !== 0){
        this.SysOperLogAndDate.startDate = this.dateTimeFile[0].toLocaleString();
        this.SysOperLogAndDate.endDate = this.dateTimeFile[1].toLocaleString()
      }
      this.SysOperLogAndDate.current = this.current
      this.SysOperLogAndDate.size = this.size
        axios.post("http://localhost:8080/sysOperLog-find", this.SysOperLogAndDate)
            .then(result => {
              if(this.SysOperLogAndDate.status !== '') {
                this.SysOperLogAndDate.status = this.SysOperLogAndDate.status === 1 ? '开启' : '关闭';
              }
              this.SysOperLogS = result.data.data.records;
              this.current = result.data.data.current;
              this.size = result.data.data.size;
              this.pages = result.data.data.pages;
              this.total = result.data.data.total;
            })
    },
    /*回填数据*/
    backFll(data){
       let BData = this.SysOperLogBackfill
      BData.operBusiness = data.title + " / " + this.convertOperType(data.businessType)
      BData.reqPath = data.operUrl
      BData.userIdIter = data.operName + " / " + data.operId + " / " + data.operLocation
      BData.reqMethod = data.requestMethod
      BData.operMethodPath = data.method
      BData.reqParameter = data.operParam
      BData.respParameter = data.jsonResult
      BData.loginStatus = data.status = 0 ? '离线' : '在线'
      BData.operTime = data.operTime
      this.SysOperLogBackfill = BData
    },
    /*清空数据*/
    clearCache(){
      this.$confirm('此操作将导致所有数据永久丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('http://localhost:8080/sysOperLog-ClearData')
            .then(result => {
              this.openYes("已全部清空！")
              this.loadFindPage(this.current);
            })
        this.$message({
          type: 'success',
          message: '已全部清空!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      //dicId属性值集合
      this.selectionList = selection.map(item => item.operId);
      //被选中个数
      this.selectionLength = selection.length;
    },
    /*消息*/
    openNotice(string) {
      this.$notify.info({
        title: '消息',
        message: string,
      });
    },
    /*成功*/
    openYes(string) {
      this.$notify({
        title: '成功',
        message: string,
        type: 'success'
      });
    },
    /*警告*/
    openWarning(string) {
      this.$notify({
        title: '警告',
        message: string,
        type: 'warning'
      });
    },
    /*错误*/
    openError(string) {
      this.$notify.error({
        title: '错误',
        message: string,
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.loadFindPage(this.current)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val;
      this.loadFindPage(val);
    },
  },
  mounted: function () {
    this.loadAll();
    this.getAllJudge();
    this.loadFindPage(1);
  },
}

</script>

<template>
  <div>
    <!--    模糊查询-->
    <p class="demo-input-suffix" style="text-align: left">

      系统模块：
      <el-input placeholder="请输入内容" prefix-icon="el-icon-search" v-model="SysOperLogAndDate.title"
                class="input-wc"></el-input>
      操作人员：
      <el-input placeholder="请输入内容" prefix-icon="el-icon-search" v-model="SysOperLogAndDate.operName"
                class="input-wc"></el-input>
      类型：
      <el-select v-model="SysOperLogAndDate.businessType" placeholder="请选择">
        <el-option
            v-for="item in AllJudge"
            :key="item.dictSort"
            :label="item.dictLabel"
            :value="item.dictSort">
        </el-option>
      </el-select>
      状态：
      <el-radio-group v-model="SysOperLogAndDate.status" style="margin-right: 20px">
        <el-radio-button label="开启"></el-radio-button>
        <el-radio-button label="关闭"></el-radio-button>
      </el-radio-group>
      操作时间：
      <el-date-picker v-model="dateTimeFile" type="daterange" align="right" unlink-panels
                      range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                      :picker-options="pickerOptions" >
      </el-date-picker>
      <el-button type="primary" icon="el-icon-search" @click="loadFindPage(1)" style="margin-left: 20px">搜索
      </el-button>
    </p>
    <!--    范围操作按钮-->
    <div>
      <p style="text-align: left">
        <!--    确认气泡-->
          <el-button type="danger" slot="reference" @click="deleteSomeSysOperLog()"><i class="el-icon-delete" style="margin-right: 10px"/>删除</el-button>
        <el-button type="danger" slot="reference" @click="clearCache()" style="margin-right: 10px"><i class="el-icon-refresh" style="margin-right: 10px"/>清除缓存</el-button>
        <el-popover placement="top" width="160" v-model="visible"  style="margin-right: 10px">
          <el-input v-model="dateName" placeholder="请设置文件名"></el-input>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="visible = false;isNull();">取消</el-button>
            <el-button type="primary" size="mini" @click="visible = false;handleDownload(dateName)">确定</el-button>
          </div>
          <el-button type="warning"  slot="reference"><i class="el-icon-download"/>导出</el-button>
        </el-popover>
      </p>
      <!--      表格显示所有数据-->
      <el-table :data="SysOperLogS" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="operId" label="日志编号" width="180"></el-table-column>
        <el-table-column prop="title" label="系统模块" width="180"></el-table-column>
        <el-table-column label="操作类型" width="180">
          <template slot-scope="scope">
            {{ convertOperType(scope.row.operatorType)}}
          </template>
        </el-table-column>
        <el-table-column prop="requestMethod" label="请求方式" width="180"></el-table-column>
        <el-table-column prop="operName" label="操作人员" width="180"></el-table-column>
        <el-table-column prop="operIp" label="主机" width="180"></el-table-column>
        <el-table-column prop="operLocation" label="操作地点" width="180"></el-table-column>
        <el-table-column label="操作状态" width="180">
          <template slot-scope="scope">
            {{ scope.row.status === 1 ? '开启' : '关闭' }}
          </template>
        </el-table-column>
        <el-table-column prop="operTime" label="操作日期"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="tableDataList">
            <el-button type="primary" icon="el-icon-tickets" @click="dialogVisible = true;backFll(tableDataList.row)" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--    显示内容-->
    <!--    分页-->
    <div class="block" style="margin-top: 10PX">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page=current :page-sizes="[10,50,100, 300, 500]" :page-size=size
                     layout="total, sizes, prev, pager, next, jumper" :total=total>
      </el-pagination>
    </div>

    <!--    弹出显示框-->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="60%"  :before-close="handleClose">
              <!--        显示框内展示内容-->
      <el-descriptions class="margin-top" title="详细信息" :column="2" :size="this.size" border>
              <el-descriptions-item label="this.SysOperLogBackfill.operBusiness"><template slot="label"><i class="el-icon-user"></i>操作模块</template>
                {{this.SysOperLogBackfill.operBusiness}}
              </el-descriptions-item>
              <el-descriptions-item><template slot="label"><i class="el-icon-mobile-phone"></i>请求地址</template>
                {{this.SysOperLogBackfill.reqPath}}
              </el-descriptions-item>
              <el-descriptions-item><template slot="label"><i class="el-icon-tickets"></i>登录信息</template>
                {{this.SysOperLogBackfill.userIdIter}}
              </el-descriptions-item>
              <el-descriptions-item><template slot="label"><i class="el-icon-location-outline"></i>请求方式</template>
                {{this.SysOperLogBackfill.reqMethod}}
              </el-descriptions-item>
              <el-descriptions-item span="2"><template slot="label"><i class="el-icon-office-building"></i>操作方式</template>
                {{this.SysOperLogBackfill.operMethodPath}}
              </el-descriptions-item>
              <el-descriptions-item span="2"><template slot="label"><i class="el-icon-office-building"></i>请求参数</template>
                {{this.SysOperLogBackfill.reqParameter}}
              </el-descriptions-item>
              <el-descriptions-item span="2"><template slot="label"><i class="el-icon-office-building"></i>返回参数</template>
                {{this.SysOperLogBackfill.respParameter}}
              </el-descriptions-item>
              <el-descriptions-item><template slot="label"><i class="el-icon-office-building"></i>操作状态</template>
                {{this.SysOperLogBackfill.loginStatus}}
              </el-descriptions-item>
              <el-descriptions-item ><template slot="label"><i class="el-icon-office-building"></i>操作时间</template>
                {{this.SysOperLogBackfill.operTime}}
              </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>
.input-wc {
  width: 200px;
  margin-right: 20px;
}
</style>
